<?php

/**
 * Manage site common settings
 * @author Tuong Tran <tuong.tran@outlook.com>
 */
class SettingController extends Controller {

    public $activeMenu = 'setting';

    /**
     * site setting general
     */
    public function actionIndex($type = 'site') {

	if (Yii::app()->request->isPostRequest) {

	    $this->_clearCacheSettingFrontEnd($type);

	    $settings = Yii::app()->settings;
	    $settings->deleteCache($type);
	    foreach ($_POST as $key => $value) {
		$settings->set($type, $key, $value);
	    }

	    Yii::app()->user->setFlash('success', 'Your settings has been updated');
	    $this->refresh();
	}

	$settings = settings()->load($type);

	$this->render($type, array(
	    'settings' => $settings
	));
    }

    /**
     * clear cache both frontend and backend
     */
    public function actionDeleteCache() {
	if (Yii::app()->request->isPostRequest) {
	    if (isset($_POST['frontend'])) {
		$this->_clearCache('frontend');
	    } elseif (isset($_POST['backend'])) {
		$this->_clearCache('backend');
	    } else {
		$this->_clearCache('frontend');
		$this->_clearCache('backend');
	    }
	    Yii::app()->user->setFlash('success', 'Deleted all cache');
	    $this->redirect(array('/setting/index'));
	}

	$this->render('delete_cache');
    }

    private function _clearCache($where) {
	switch ($where) {
	    case 'frontend':
		//Send Post Request to Frontend
		$timeout = 30;
		$curl = curl_init();
		$pvars = array('key' => FRONTEND_CLEAR_CACHE_KEY);
		curl_setopt($curl, CURLOPT_URL, FRONT_SITE_URL . 'site/caching');
		curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
		$result = curl_exec($curl);
		curl_close($curl);

		return $result == '0' ? false : true;
		break;
	    case 'backend':
		Yii::app()->cache->flush();
		return true;
		break;
	}
    }

    /**
     * clear cache setting by category on frontend
     */
    private function _clearCacheSettingFrontEnd($category) {
	//Send Post Request to Frontend
	$timeout = 30;
	$curl = curl_init();
	$pvars = array('setting' => 1, 'category' => $category);
	curl_setopt($curl, CURLOPT_URL, FRONT_SITE_URL . 'site/caching');
	curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
	curl_setopt($curl, CURLOPT_POST, 1);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
	$result = curl_exec($curl);
	curl_close($curl);
    }

}

